package com.xy.tool.data.redis.ex;

import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class HashOperationsEx<V> {

    private final RedisTemplate<String, V> redisTemplate;
    private final HashOperations<String, String, V> hashOps;

    public HashOperationsEx(RedisTemplate<String, V> redisTemplate) {
        Objects.requireNonNull(redisTemplate);
        this.redisTemplate = redisTemplate;
        this.hashOps = redisTemplate.opsForHash();
    }

    public Map<String, V> scan(String key, String pattern, int scanSize) {
        Objects.requireNonNull(key, "The key is required.");
        if(scanSize < 1) {
            throw new IllegalArgumentException("The scanSize should be than 0.");
        }
        String pattern0 = (pattern == null) ? "" : pattern;
        Map<String, V> valueMap = new HashMap<>();
        Cursor<Map.Entry<String, V>> cursor = hashOps.scan(key,
                new ScanOptions.ScanOptionsBuilder()
                        .match(pattern0.concat("*"))
                        .count(scanSize)
                        .build());
        Map.Entry<String, V> entry;
        while (cursor.hasNext()) {
            entry = cursor.next();
            valueMap.put(entry.getKey(), entry.getValue());
        }
        return valueMap;
    }

}
